class GridsDatatable
  delegate :params, :session, :raw, :link_to, :number_to_currency, :best_in_place, to: :@view

  def initialize(view, current_user)
    @view = view
    @current_user = current_user
  end

  def as_json(options = {})
    {
      sEcho: params[:sEcho].to_i,
      iTotalRecords: fetch_data_count,
      iTotalDisplayRecords: fetch_data_count,
      aaData: aa_data
    }
  end

  private

  def aa_data
    search_scope.order("#{sort_column} #{sort_direction}").skip(skip_num).limit(per_page).map do |record|
      rows = []
      rows << record.code
      rows << record.name
      rows << record.created_at.strftime('%F %T')
      rows << %{
        #{link_to('详细', "#{@view.cpanel_grid_path(record)}", class: 'btn btn-outline btn-default') + raw('&nbsp;&nbsp;')}
        #{link_to('修改', "#{@view.edit_cpanel_grid_path(record)}", class: 'btn btn-outline btn-default') + raw('&nbsp;&nbsp;')}
        #{link_to('删除', "#{@view.cpanel_grid_path(record)}", class: 'btn btn-outline btn-danger', method: :delete, remote: true, data: { confirm: '删除后不可恢复,确定删除吗?' })}
      }
      rows
    end
  end

  def fetch_data_count
    @data_count ||= search_scope.count
  end

  def search_scope
    search_params = {}
    s_search      = params[:sSearch]
    search_params = { '$or' => [{ name: /#{s_search}/ }, { code: /#{s_search}/ }] } if s_search.present?
    Grid.where(search_params)
  end

  def skip_num
    (params[:iDisplayStart].to_i / per_page) * per_page
  end

  def per_page
    params[:iDisplayLength].to_i.positive? ? params[:iDisplayLength].to_i : 25
  end

  def sort_column
    columns = %w(code name created_at created_at)
    columns[params[:iSortCol_0].to_i]
  end

  def sort_direction
    params[:sSortDir_0] == 'desc' ? 'desc' : 'asc'
  end
end
